package com.lagou.edu.transactional;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

@Aspect
@Component
public class Aop {
    @Autowired
    private MyTransactionManager myTransactionManager;

    @Around("@annotation(com.lagou.edu.transactional.MyTransactional)")
    public Object doTransaction(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object o = null;
        Connection connection = myTransactionManager.getConnection();
        try {
            connection.setAutoCommit(false);
            o = proceedingJoinPoint.proceed();
            connection.commit();

        } catch (SQLException e) {
            e.printStackTrace();
            connection.rollback();
        }finally {
            connection.close();
        }
        return o;
    }
}
